package service

import (
	"errors"
	"go-frame/src/server-admin/dao"
	"go-frame/src/server-admin/models"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/google/uuid"
	"golang.org/x/crypto/bcrypt"
)

// var jwtSecret = []byte("your_secret_key") // 替换为您的密钥

type AuthService struct {
	UserDAO                *dao.UserDAO
	ExpirationMilliseconds int
	Secret                 []byte
}

func NewAuthService(userDAO *dao.UserDAO, expirationMilliseconds int, secret string) *AuthService {
	return &AuthService{UserDAO: userDAO, ExpirationMilliseconds: expirationMilliseconds, Secret: []byte(secret)}
}

func (s *AuthService) Register(username, password, email string) error {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}

	user := &models.User{
		UUID:     uuid.New().String(),
		Username: username,
		Password: string(hashedPassword),
		Email:    email,
	}

	return s.UserDAO.CreateUser(user)
}

func (s *AuthService) Login(username, password string) (string, error) {
	user, err := s.UserDAO.GetUserByUsername(username)
	if err != nil {
		return "", errors.New("用户不存在或密码错误")
	}

	err = bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
	if err != nil {
		return "", errors.New("用户不存在或密码错误")
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"username": user.Username,
		"uuid":     user.UUID,
		"exp":      time.Now().Add(time.Duration(s.ExpirationMilliseconds) * time.Millisecond).Unix(), // Token 有效期
	})

	tokenString, err := token.SignedString(s.Secret)
	if err != nil {
		return "", err
	}

	return tokenString, nil
}

func (s *AuthService) ParseToken(tokenString string) (*jwt.MapClaims, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("非法的签名方法")
		}
		return s.Secret, nil
	})

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return &claims, nil
	}
	return nil, err
}

func (s *AuthService) GetUserByID(id uint) (*models.User, error) {
	return s.UserDAO.GetUserByID(id)
}

func (s *AuthService) GetUserByUUID(uuid string) (*models.User, error) {
	return s.UserDAO.GetUserByUUID(uuid)
}
